<?php

class sbBooking {

    public function info($hotel_id, $rooms_id, $count, $token) {
        $parse_room = explode(';', $rooms_id);
        $parse_count = explode(';', $count);
        $hotel = $this->getHotel($hotel_id);
        $rooms = $this->getRooms($parse_room, $parse_count, $this->parseToken($token));

        $fullHotel = $hotel->toArray();
        $fullHotel[0]['Rooms'] = $rooms;
        return $fullHotel[0];
    }

    public function getHotel($hotel_id) {
        return Doctrine_Query::create()->
                        select('r.*, c.name_en, g.name_en, s.name_en')->
                        from('tblHotel r')->
                        leftJoin('r.CountryHotel c')->
                        leftJoin('r.RegionHotel g')->
                        leftJoin('r.CityHotel s')->
                        where('r.id=?', $hotel_id)->
                        execute();
    }

    public function getRooms($rooms, $count, $token) {
        $arrRooms = array();
        for ($i = 0; $i < count($rooms); $i++) {
            $room = Doctrine_Query::create()->
                    select('*')->
                    from('tblRooms')->
                    where('id=?', $rooms[$i])->
                    execute();
            $roomToArray = $room->toArray();
            $roomToArray[0]['SearchResult'] = array(
                'token' => $token[$i]
            );
            array_push($arrRooms, $roomToArray);
        }

        $allRooms = array();
        for ($i = 0; $i < count($count); $i++) {
            for ($j = 0; $j < $count[$i]; $j++) {
                array_push($allRooms, $arrRooms[$i]);
            }
        }

        return $allRooms;
    }

    public function parseGuests($guests) {
        $array = explode(';', $guests);

        $arrayGuests = array();
        for ($i = 0; $i < count($array) - 1; $i++) {
            $ar = explode(':', $array[$i]);
            $temp = array(
                'adult' => $ar[1],
                'children' => $ar[2],
                'babeis' => $ar[3]
            );
            array_push($arrayGuests, $temp);
        }

        return $arrayGuests;
    }

    public function parseToken($token) {
        $array = explode(';', $token);

        $arrayToken = array();
        for ($i = 0; $i < count($array) - 1; $i++) {
            array_push($arrayToken, $array[$i]);
        }

        return $arrayToken;
    }

    public function payment($user_id) {
        if (is_null($user_id) || $user_id == 0) {
            return array(
                array('type' => 'Rest Agent', 'value' => sbValues::PAYLOADS_BY_AGEND, 'input' => 'Agent Locator')
            );
        } else {
            $user = tblUsersTable::getInstance()->findByDql('id=?', $user_id)->getFirst();
            switch ($user->getPermissions()) {
                case sbValues::PERMISSIONS_STANDART:
                    return array(
                        array('type' => 'PayPal', 'value' => sbValues::PAYLOADS_PAYPAL, 'input' => ''),
                        array('type' => 'Rest Agent', 'value' => sbValues::PAYLOADS_BY_AGEND, 'input' => 'Agent Locator'),
                        array('type' => 'By Phone', 'value' => sbValues::PAYLOADS_BY_PHONE, 'input' => 'Call to Phone number +972 3 510 90 40')
                    );
                case sbValues::PERMISSIONS_AGENT || sbValues::PERMISSIONS_FIRM || sbValues::PERMISSIONS_ADMIN:
                    return array(
                        array('type' => 'PayPal', 'value' => sbValues::PAYLOADS_PAYPAL, 'input' => ''),
                        array('type' => 'From your Balance', 'value' => sbValues::PAYLOADS_BY_BALANCE, 'input' => $user->getBalance()),
                        array('type' => 'By Phone', 'value' => sbValues::PAYLOADS_BY_PHONE, 'input' => 'Call to Phone number +972 3 510 90 40')
                    );
            }
        }
    }

    public function requestBooking($id, $post) {
        $hotel_id = $post['hotel_id'];
        $rooms_id = $post['rooms_ids'];
        $price = $post['price'];
        $sessions = $post['sessions'];
        $guest_title = $post['guest_title'];
        $first_name = $post['first_name'];
        $last_name = $post['last_name'];
        $passports = $post['passports'];
        $date_in = $post['date_in'];
        $days = $post['days'];
        $board = $post['board'];
        $smoking = $post['smoking'];
        $bed = $post['bed'];
        $payment = $post['payment'];

        if ($this->checkUserPayments(sbUser::getUserData($id), $payment, $price)) {
            $result = $this->processBooking(sbHotels::hotelData($hotel_id), $this->parseBookingRooms($rooms_id, $board, $smoking, $bed, $sessions), $this->parseGuestName($first_name, $last_name, $guest_title, $passports), $date_in, $days);
            $order_id = $this->saveOrder($id, $hotel_id, $rooms_id, $price, $this->parseGuestName($first_name, $last_name, $guest_title, $passports), $date_in, $days, $result, $payment);
            return $order_id;
        } else {
            return array('status' => 'error', 'data' => 'Orders from the loan is not possible.');
        }
    }

    public function processBooking($hotel, $rooms, $guest, $date_in, $days) {
        switch ($hotel->getProviderId()) {
            case sbValues::PROVIDER_ISR:
                $isr = new sbIsratel();
                $client = $isr->connect();
                foreach ($rooms as $r) {
                    $token = $isr->getReservationParams($client, $r['session']);
                    $result = $isr->parseReservationParams($token);
                    if ($result) {
                        $reserve = $isr->makeReservation($client, $result['token'], $r['session'], $guest[0]);
                        $book = $isr->parseMakeReservation($reserve);
                        return $book;
                    }
                }
                break;
            case sbValues::PROVIDER_GOC:
                $goc = new sbGoc();
                $client = $goc->connect();
                if ($client['status']) {
                    foreach ($rooms as $r) {

                        $save = $goc->saveBooking($client['cause'], $hotel->getProviderCode(), $r['session'], $date_in, $days, $guest[0]['first_name'], $guest[0]['last_name']);
                        $book = $goc->parseSave($save);
                        return $book;
                    }
                } else {
                    return 'not connection to goc provider';
                }
        }
    }

    public function checkUserPayments($user, $payment, $price) {
        switch ($payment) {
            case sbValues::PAYLOADS_BY_BALANCE:
                $credit = $user->getBalance() + $user->getCredit();
                if ($credit >= $price) {
                    return true;
                } else {
                    return false;
                }
            case sbValues::PAYLOADS_PAYPAL:
                return 'not work alredy';
        }
    }

    public function parseBookingRooms($rooms_id, $board, $smoking, $bed, $sessions) {
        $parseRooms = explode(';', $rooms_id);
        $parseBoard = explode(';', $board);
        $parseSmoking = explode(';', $smoking);
        $parseBed = explode(';', $bed);
        $parseSessions = explode(';', $sessions);
        $roomsArray = array();
        for ($i = 0; $i < count($parseRooms) - 1; $i++) {
            $r = tblRoomsTable::getInstance()->findByDql('id=?', $parseRooms[$i])->getFirst();
            $temp = array(
                'local_id' => $r->getId(),
                'provider_id' => $r->getCodeName(),
                'board' => $parseBoard[$i],
                'smoking' => $parseSmoking[$i],
                'bed' => $parseBed[$i],
                'session' => $parseSessions[$i]
            );
            array_push($roomsArray, $temp);
        }

        return $roomsArray;
    }

    public function parseGuestName($first_name, $last_name, $title, $passports) {
        $parseFirst = explode(';', $first_name);
        $parseLast = explode(';', $last_name);
        $parseTitle = explode(';', $title);
        $parsePassports = explode(';', $passports);
        $guests = array();
        for ($i = 0; $i < count($parseFirst) - 1; $i++) {
            $temp = array(
                'title' => $parseTitle[$i],
                'first_name' => $parseFirst[$i],
                'last_name' => $parseLast[$i],
                'passport_id' => $parsePassports[$i],
            );
            array_push($guests, $temp);
        }

        return $guests;
    }

    public function saveOrder($id, $hotel_id, $rooms_id, $price, $guests, $date_in, $days, $result, $payment) {
        if ($result) {
            $order = new tblOrders();
            $order->setUserId($id);
            $order->setProviderId($result['reservation_id']);
            $order->setProviderOrder($result['reservation_stirng']);
            $order->setMainFirstName($guests[0]['first_name']);
            $order->setMainLastName($guests[0]['last_name']);
            $order->setFromDate($date_in);
            $order->setToDate(date('Y-m-d', strtotime($date_in . '+' . $days . 'days')));
            $order->setHotelId($hotel_id);
            $order->setRoomsId($rooms_id);
            $order->setTypePrice(sbValues::USER_TOURIST);
            $order->setPaymentType($payment);
            $order->setAmount($price);
            $order->setCreateBy(sbValues::getCurrentTime());
            $order->save();

            $agent = tblUsersTable::getInstance()->findByDql('id=?', $id)->getFirst();
            $balance = $agent->getBalance();
            $orders = $agent->getOrders();
            $agent->setBalance($balance - $price);
            $agent->setOrders($orders++);
            $agent->save();

            return array('status' => 'success', 'data' => $order->getId());
        } else {
            return array('status' => 'error', 'data' => 'try again');
        }
    }

    public function currentBooking($order_id) {
        $order = tblOrdersTable::getInstance()->findByDql('id=?', $order_id)->getFirst();
        if ($order) {
            $hotel = sbHotels::hotelData($order->getHotelId());
            $parseRooms = explode(';', $order->getRoomsId());
            $arrayRooms = array();
            for ($i = 0; $i < count($parseRooms) - 1; $i++) {
                $temp = tblRoomsTable::getInstance()->findByDql('id=?', $parseRooms[$i])->getFirst();
                $r = $temp->toArray();
                array_push($arrayRooms, $r);
            }

            $result = array(
                'order' => $order->toArray(),
                'hotel' => $hotel->toArray(),
                'rooms' => $arrayRooms
            );

            return $result;
        }
    }

}
